package com.example.mybatisplusdemo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.mybatisplusdemo.common.utls.SessionUtils;
import com.example.mybatisplusdemo.model.domain.Merchant;
import com.example.mybatisplusdemo.mapper.MerchantMapper;
import com.example.mybatisplusdemo.model.domain.User;
import com.example.mybatisplusdemo.service.IMerchantService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.util.Random;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author lxp
 * @since 2025-07-04
 */
@Service
public class MerchantServiceImpl extends ServiceImpl<MerchantMapper, Merchant> implements IMerchantService {

    @Autowired
    private MerchantMapper merchantMapper;

    private static final Random RANDOM = new Random();

    public boolean isUsernameRepeat(String username) {
        LambdaQueryWrapper<Merchant> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Merchant::getUsername, username);
        return merchantMapper.selectCount(wrapper) > 0;
    }

    //随机生成10位账号
    public String generateUsername() {
        StringBuilder sb = new StringBuilder(10);
        sb.append(RANDOM.nextInt(9) + 1);
        for (int i = 1; i < 10; i++) {
            sb.append(RANDOM.nextInt(10));
        }
        return sb.toString();
    }

    @Override
    public Merchant loginByUsername(Merchant merchant) {
        LambdaQueryWrapper<Merchant> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Merchant::getUsername, merchant.getUsername()).eq(Merchant::getPassword, merchant.getPassword());
        Merchant one = merchantMapper.selectOne(queryWrapper);
        SessionUtils.saveCurrentMerchantInfo(one);
        return one;
    }

    @Override
    public Merchant loginByPhone(Merchant merchant) {
        LambdaQueryWrapper<Merchant> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Merchant::getPhone, merchant.getPhone()).eq(Merchant::getPassword, merchant.getPassword());
        Merchant one = merchantMapper.selectOne(queryWrapper);
        SessionUtils.saveCurrentMerchantInfo(one);
        return one;
    }

    @Override
    public Merchant loginByEmail(Merchant merchant) {
        LambdaQueryWrapper<Merchant> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Merchant::getEmail, merchant.getEmail()).eq(Merchant::getPassword, merchant.getPassword());
        Merchant one = merchantMapper.selectOne(queryWrapper);
        SessionUtils.saveCurrentMerchantInfo(one);
        return one;
    }

    @Override
    public Merchant loginByWechat(Merchant merchant) {
        LambdaQueryWrapper<Merchant> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Merchant::getWechatId, merchant.getWechatId()).eq(Merchant::getPassword, merchant.getPassword());
        Merchant one = merchantMapper.selectOne(queryWrapper);
        SessionUtils.saveCurrentMerchantInfo(one);
        return one;
    }

    @Override
    public boolean registerByPhone(Merchant merchant) {
        LambdaQueryWrapper<Merchant> wrapperPhone = new LambdaQueryWrapper<>();
        wrapperPhone.eq(Merchant::getPhone, merchant.getPhone());
        if (merchantMapper.selectCount(wrapperPhone) > 0)
            return false;
        //后台生成账号
        String username = generateUsername();
        while (isUsernameRepeat(username))
            username = generateUsername();
        merchant.setUsername(username);
        merchant.setRegisteredAt(LocalDate.now());
        merchant.setStatus((byte) 1);
        SessionUtils.saveCurrentMerchantInfo(merchant);
        return true;
    }

    @Override
    public boolean registerByEmail(Merchant merchant) {
        LambdaQueryWrapper<Merchant> wrapperEmail = new LambdaQueryWrapper<>();
        wrapperEmail.eq(Merchant::getEmail, merchant.getEmail());
        if (merchantMapper.selectCount(wrapperEmail) > 0)
            return false;
        //后台生成账号
        String username = generateUsername();
        while (isUsernameRepeat(username))
            username = generateUsername();
        merchant.setUsername(username);
        merchant.setRegisteredAt(LocalDate.now());
        merchant.setStatus((byte)1);
        SessionUtils.saveCurrentMerchantInfo(merchant);
        return true;
    }

    @Override
    public boolean registerByWechat(Merchant merchant) {
        LambdaQueryWrapper<Merchant> wrapperWechat = new LambdaQueryWrapper<>();
        wrapperWechat.eq(Merchant::getWechatId, merchant.getWechatId());
        if (merchantMapper.selectCount(wrapperWechat) > 0)
            return false;
        //后台生成账号
        String username = generateUsername();
        while (isUsernameRepeat(username))
            username = generateUsername();
        merchant.setUsername(username);
        merchant.setRegisteredAt(LocalDate.now());
        merchant.setStatus((byte)1);
        SessionUtils.saveCurrentMerchantInfo(merchant);
        return true;
    }

    @Override
    public boolean freezeById(Long id) {
        return merchantMapper.freezeById(id);
    }

    @Override
    public boolean unFreezeById(Long id) {
        return merchantMapper.unfreezeById(id);
    }

    @Override
    public Page<Merchant> listMerchants(Page<Merchant> page, Merchant merchant) {
        return merchantMapper.listMerchants(page, merchant);
    }


    @Override
    public boolean merchantRegister(Merchant registerData) {
        //检查账号号是否存在
        if (StringUtils.isNotBlank(registerData.getUsername())) {
            if (merchantMapper.selectOne(new QueryWrapper<Merchant>().eq("username",registerData.getUsername())) != null) {
                throw new RuntimeException("账号已被注册");
            }
        }

        //检查手机号是否存在
        if (StringUtils.isNotBlank(registerData.getPhone())) {
            if (merchantMapper.selectOne(new QueryWrapper<Merchant>().eq("phone",registerData.getPhone())) != null) {
                throw new RuntimeException("手机号已被注册");
            }
        }

        //检查邮箱是否存在
        if (StringUtils.isNotBlank(registerData.getEmail())) {
            if (merchantMapper.selectOne(new QueryWrapper<Merchant>().eq("email",registerData.getEmail())) != null) {
                throw new RuntimeException("邮箱已被注册");
            }
        }

        //创建新商家
        Merchant newMerchant= new Merchant();
        newMerchant.setUsername(registerData.getUsername());
        newMerchant.setNickname(registerData.getNickname());
        newMerchant.setPassword(registerData.getPassword());
        newMerchant.setPhone(registerData.getPhone());
        newMerchant.setEmail(registerData.getEmail());
        newMerchant.setWechatId(registerData.getWechatId());

        //设置默认字段
        newMerchant.setAvatarUrl("default_avatar_url"); // 默认头像
        newMerchant.setRegisteredAt(LocalDate.now());
        newMerchant.setStatus((byte) 1); // 状态：1-启用
        newMerchant.setDeleted(false);

        //插入数据库
        return merchantMapper.insert(newMerchant) > 0;
    }


}
